import { Button, Modal, Input, Form, Space, message, InputNumber } from "antd";
import { useState, forwardRef, useImperativeHandle, useRef } from "react";
const { TextArea } = Input;
import EditTable from "./EditTable";

export default forwardRef((props, ref) => {
  const [open, setOpen] = useState(false);
  const tableRef = useRef(null);
  const [form] = Form.useForm();
  const [titleType, setTitleType] = useState(0);

  const submitForm = async () => {
    let res = await form.validateFields();
    await tableRef.current.editForm.validateFields();
    if (!tableRef.current.dataSource.length) {
      message.warning("题目选项不能为空");
    } else {
      let params = {
        ...res,
        questionSort: res.questionSort ? res.questionSort : 0,
        options: JSON.stringify([...tableRef.current.dataSource]),
      };
      props.submitFormFun(params);
    }
  };

  useImperativeHandle(ref, () => ({
    setOpen,
    form,
    tableRef,
    setTitleType,
  }));

  return (
    <Modal
      open={open}
      title={titleType ? "编辑题目" : "新建题目"}
      forceRender
      width="60%"
      onCancel={() => setOpen(!open)}
      footer={
        <Space>
          <Button onClick={() => setOpen(false)}>取消</Button>
          <Button onClick={submitForm} type="primary">
            确定
          </Button>
        </Space>
      }
    >
      <Form
        form={form}
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 18 }}
        initialValues={{ questionSort: 0 }}
      >
        <Form.Item name="id" hidden>
          <Input />
        </Form.Item>

        <Form.Item
          label="题目标题"
          name="questionStem"
          rules={[{ required: true, message: "请输入题目标题" }]}
        >
          <Input maxLength={30} showCount />
        </Form.Item>

        <Form.Item
          label="题目分值"
          name="score"
          rules={[{ required: true, message: "请输入题目分值" }]}
        >
          <InputNumber min={0} max={100} style={{ width: "100%" }} />
        </Form.Item>

        <Form.Item label="显示顺序" name="questionSort">
          <InputNumber
            min={0}
            max={10000}
            precision={0}
            controls={false}
            style={{ width: "100%" }}
            placeholder="请输入显示顺序,输入的值越大，展示越靠前"
          />
        </Form.Item>
        <Form.Item
          label="解析内容"
          name="resultExplain"
          rules={[{ required: true, message: "请输入解析内容" }]}
        >
          <TextArea
            rows={4}
            maxLength={100}
            showCount
            placeholder="请输入解析内容"
          />
        </Form.Item>
      </Form>
      <EditTable ref={tableRef} />
    </Modal>
  );
});
